package ${packageName}.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.topxgun.core.utils.StringUtils;
import ${packageName}.dao.${className}Dao;
import ${packageName}.entity.${className}Entity;

/**
 * @See 此处添加类注释
 *
 */
@Repository("${table}Dao")
public class ${className}DaoImpl implements ${className}Dao{
	
	/**
     * 由springboot自动注入，默认配置会产生mongoTemplate这个bean
     */
    @Autowired
	@Qualifier("tagri")
    private MongoTemplate mongoTemplate;
    
	@Override
	public ${className}Entity selectById(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), ${className}Entity.class);
	}

	@Override
	public void update(${className}Entity ${table}) {
		Criteria criteria = Criteria.where("_id").is(${table}.get_id());
		Query query = new Query(criteria);
		//TODO(编辑自己的查询条件)
		Update update = Update.update("updated", new Date());
		<#list attrs as item>
		if(${table}.get${item.caseAttr}() != null){
			update.set("${item.attr}", ${table}.get${item.caseAttr}());
		}
		</#list>
		mongoTemplate.updateMulti(query, update, ${className}Entity.class);
	}

	@Override
	public void insert(${className}Entity ${table}) {
		mongoTemplate.insert(${table});
	}

	@Override
	public void delete(String id) {
		Criteria criteria = Criteria.where("_id").is(id);
        Query query = new Query(criteria);
        mongoTemplate.remove(query,${className}Entity.class);
	}

	
	@Override
	public List<${className}Entity> listByMap(Map<String, Object> param) {
		Criteria criteria = new Criteria();
		int indexOfMap = 1;
		for(Map.Entry<String, Object> item : param.entrySet()){
			if(!String.valueOf(item.getValue()).isEmpty() && item.getValue() != null){
				if(indexOfMap == 1){
					criteria=Criteria.where(item.getKey()).is(item.getValue());
				}else {
					criteria.and(item.getKey()).is(item.getValue());
				}
				indexOfMap++;
			}
		}
	    Query query = new Query(criteria);
		// 查询
	    List<${className}Entity> list = mongoTemplate.find(query,${className}Entity.class);
		return list;
	}

}
